import 'package:flutter/material.dart';
import 'package:flutter_account_book/utils/db/entities/account_record.dart';
import 'package:flutter_account_book/utils/eventbus.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:sticky_headers/sticky_headers/widget.dart';

import '../logic.dart';

class AccountChildPage extends StatefulWidget {
  final int curId;

  const AccountChildPage({super.key, required this.curId});

  @override
  State<StatefulWidget> createState() => _AccountChildPage();
}

class AccountGroupItem {
  final String title;
  final DateTime dateTime;
  final List<AccountRecord> list;

  AccountGroupItem(
      {required this.title, required this.dateTime, required this.list});
}

// showPlaceholderPage(
//             show: true,
//             placeholder: "请点击下方+，添加一条账目吧~",
//             child:
class _AccountChildPage extends State<AccountChildPage> {
  MyHomeLogic get _logic => Get.find<MyHomeLogic>();

  RxDouble income = 0.0.obs;
  RxDouble expend = 0.0.obs;
  RxDouble curMonthIncome = 0.0.obs;
  RxDouble curMonthExpend = 0.0.obs;

  RxList<AccountGroupItem> list = RxList();

  @override
  void initState() {
    super.initState();

    getHeaderInfo();
    getGroupItems();

    eventBus.on<AddRecordEvent>().listen((event) {
      getHeaderInfo();
      getGroupItems();
    });
  }

  getHeaderInfo() {
    _logic.getTotalExpend(widget.curId).then((onValue) {
      expend.value = onValue;
    });
    _logic.getTotalIncome(widget.curId).then((onValue) {
      income.value = onValue;
    });
    _logic.getCurMonthTotalExpend(widget.curId).then((onValue) {
      curMonthExpend.value = onValue;
    });
    _logic.getCurMonthTotalIncome(widget.curId).then((onValue) {
      curMonthIncome.value = onValue;
    });
  }

  getGroupItems() async {
    final list = await _logic.getAccountRecordList(widget.curId);
    Map<String, List<AccountRecord>> groupedItems = {};
    for (var item in list) {
      DateTime time = DateTime.fromMillisecondsSinceEpoch(item.recordTime);
      String day = DateFormat('yyyy-MM-dd').format(time);
      if (groupedItems[day] == null) {
        groupedItems[day] = [];
      }
      groupedItems[day]?.add(item);
    }

    List<MapEntry<String, List<AccountRecord>>> sortedEntries =
        groupedItems.entries.toList()..sort((a, b) => b.key.compareTo(a.key));

    List<AccountGroupItem> items = [];
    for (var entry in sortedEntries) {
      items.add(AccountGroupItem(
          title: entry.key,
          dateTime: DateFormat('yyyy-MM-dd').parse(entry.key),
          list: entry.value));
    }
    this.list.value = items;
  }

  @override
  Widget build(BuildContext context) {
    ThemeData themeData = Theme.of(context);
    return CustomScrollView(
      slivers: <Widget>[
        SliverPersistentHeader(
          delegate: _SliverAppBarDelegate(
              minHeight: 24.0,
              maxHeight: 150.0,
              child: Padding(
                  padding: const EdgeInsets.all(10),
                  child: Card(
                      child: Column(children: [
                    Container(
                        padding: EdgeInsets.fromLTRB(20, 20, 20, 10),
                        child: Row(
                          children: [
                            Text('总资产：',
                                style: TextStyle(
                                    fontSize: 23, fontWeight: FontWeight.bold)),
                            Obx(() => Text('${income.value - expend.value}',
                                style: TextStyle(
                                    fontSize: 23, fontWeight: FontWeight.bold)))
                          ],
                        )),
                    Row(
                      children: [
                        Expanded(
                            flex: 1,
                            child: Center(
                                child: Column(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                Obx(() => Text('${curMonthExpend.value}',
                                    style: TextStyle(fontSize: 18.0))),
                                Text('本月支出',
                                    style: TextStyle(
                                        fontSize: 16.0,
                                        color: themeData.indicatorColor))
                              ],
                            ))),
                        Center(
                            child: Container(
                                color: Colors.grey, width: 0.5, height: 20)),
                        Expanded(
                            flex: 1,
                            child: Center(
                                child: Column(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                Obx(() => Text('${curMonthIncome.value}',
                                    style: TextStyle(fontSize: 18.0))),
                                Text('本月收入',
                                    style: TextStyle(
                                        fontSize: 16.0,
                                        color: themeData.indicatorColor))
                              ],
                            )))
                      ],
                    )
                  ]))),
              hiddenChild: Container(
                color: themeData.scaffoldBackgroundColor,
                padding: const EdgeInsets.fromLTRB(0, 0, 10, 0),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    Text('支出：${expend.value}',
                        style: TextStyle(fontSize: 12.0)),
                    Center(
                        child: Container(
                            margin: EdgeInsets.fromLTRB(10, 0, 10, 0),
                            color: Colors.grey,
                            width: 1,
                            height: 10)),
                    Text('收入：${income.value}', style: TextStyle(fontSize: 12.0))
                  ],
                ),
              )),
          pinned: true,
        ),
        Obx(() => SliverList(
              delegate: SliverChildBuilderDelegate(
                (BuildContext context, int index) {
                  final obj = list[index];
                  return StickyHeader(
                      header: Padding(
                          padding: EdgeInsets.fromLTRB(0, 20, 0, 0),
                          child: Container(
                            height: 33.0,
                            color: themeData.scaffoldBackgroundColor,
                            padding: EdgeInsets.symmetric(horizontal: 16.0),
                            alignment: Alignment.centerLeft,
                            child: Text(
                              obj.title,
                              style: const TextStyle(color: Colors.black),
                            ),
                          )),
                      content: Column(
                          children: List.generate(obj.list.length, (itemIndex) {
                        final item = obj.list[itemIndex];
                        return ListTile(
                          leading:
                              _logic.buildIcon(item.recordTypeId, themeData),
                          title: Text(item.recordType),
                          subtitle:
                              item.remark != null && item.remark!.isNotEmpty
                                  ? Text("备注：${item.remark}")
                                  : null,
                          trailing:
                              Row(mainAxisSize: MainAxisSize.min, children: [
                            Text(
                                '${item.isIncome == 0 ? "-" : "+"}${item.amount}'),
                            const SizedBox(width: 8),
                            _logic.buildPayIcon(item.payMethodId)
                          ]),
                        );
                      })));
                },
                childCount: list.length,
              ),
            )),
      ],
    );
  }
}

class _SliverAppBarDelegate extends SliverPersistentHeaderDelegate {
  _SliverAppBarDelegate({
    required this.minHeight,
    required this.maxHeight,
    required this.child,
    required this.hiddenChild,
  });

  final double minHeight;
  final double maxHeight;
  final Widget child;
  final Widget hiddenChild;

  @override
  double get minExtent => minHeight;

  @override
  double get maxExtent => maxHeight;

  @override
  Widget build(
      BuildContext context, double shrinkOffset, bool overlapsContent) {
    return shrinkOffset > 10
        ? SizedBox.expand(child: hiddenChild)
        : Transform.translate(
            offset: Offset(0, shrinkOffset * -1),
            child: Opacity(
              opacity: (10 - shrinkOffset) / 10,
              child: SizedBox(height: maxHeight, child: child),
            ));
  }

  @override
  bool shouldRebuild(_SliverAppBarDelegate oldDelegate) {
    return maxHeight != oldDelegate.maxHeight ||
        minHeight != oldDelegate.minHeight ||
        child != oldDelegate.child;
  }
}
